<?php

class OrderMode extends SiteMode {
    /** @return OrderMode */
    public static function init() {
        return parent::init();
    }
    //重写下单
    function create($user_id,$shop_id,$goodsArray,$type = 'normal',
                    $order_amount,$payment_amount,$user_address_id,$point = null,
                    $user_coupon_id = null, $service_id = null, $buyer_id = null,$remark = null){
        $this->db->beginTransaction();
        $totalAmount=0.0;
        //获得goods_ids
        $goods_ids_arr=array();
        foreach ($goodsArray as $value) {
            $goods_ids_arr[]=$value['goods_id'];
            $price_id=GoodsMode::init()->getPriceId($value['goods_id'],false);
            $price=GoodsMode::init()->getPriceByNum($price_id,$value['number']);
            $totalAmount+=$price*$value['number'];
        }
        //判断point<=paymen_amount*10%
        $userInfo=UserMode::init()->getDetailWithoutJoin($user_id);
        $point = $point<=$totalAmount*10.0? $point : $totalAmount*10.0;
        $point = $point > $userInfo['point']? $userInfo['point']:$point;
        //couponValue
        if(!empty($user_coupon_id)){
            $coupon_value=CouponMode::init()->getValueByUser($user_coupon_id);
        }else{
            $coupon_value=0.0;
        }
        //存入order表
        $data['user_id']=empty($buyer_id)?$user_id:$buyer_id;
        $data['shop_id']=$shop_id;
        $data['goods_ids']=implode(',',$goods_ids_arr);
        $data['user_address_id']=$user_address_id;
        $data['service_id']=$service_id;
        $data['order_amount']=$totalAmount;
        $data['payment_amount']=(double)$totalAmount-(double)$point*0.001-(int)$coupon_value;
        $data['point']=$point;
        $data['user_coupon_id']=$user_coupon_id;
        $data['state']='unpaid';
        $data['type']=$type;
        $data['buyer_id']=empty($buyer_id)?null:$user_id;
        $data['remark']=empty($remark)?null:$remark;
        $data['site_id']=$this->siteId;
        if( $this->db->insert('order',$data) == 1 ){
            $order_id = (int)$this->db->insertId();
            $flag = true;
            //存入goods_in_order表
            foreach ($goodsArray as $k=>$v) {
                $flag &= $this->addGoodsInOrder($order_id,$v['goods_id'],$v['attr_id'],$v['number'],$v['share_id']);
            }
            if($flag){
                $this->db->commit();
                return $order_id;
            }
        }
        $this->db->rollBack();
        return -1;
    }
    //添加到goods_in_order表
    function addGoodsInOrder($order_id,$goods_id,$attr_id,$number,$share_id){
        $data['order_id']=$order_id;
        $data['goods_id']=$goods_id;
        $data['attr_id']=$attr_id;
        $data['number']=$number;
        $data['share_id']=$share_id;
        $data['site_id']=$this->siteId;
        return $this->db->insert('goods_in_order',$data)==1? true:false;
    }
    //获得订单状态
    function getState($order_id){
        $sql = "SELECT `state` FROM `order` WHERE `id`=? and site_id=?";
        return $this->db->getValue($sql,$order_id,$this->siteId);
    }
    //设置订单状态
    function setState($order_id,$state){
        $data['state']=$state;
        switch($state){
            case 'unshipped':
            case 'unused':  $data['payment_time']=date("Y-m-d H:i:s",time()); break;
            case 'shipped':
            case 'shipped_direct':
                $data['shipping_time']=date("Y-m-d H:i:s",time()); break;
            case 'service': $data['service_time']=date("Y-m-d H:i:s",time()); break;
            case 'received': $data['delivery_time']=date("Y-m-d H:i:s",time()); break;
            case 'confirmed': case 'used':
                $data['deal_time']=date("Y-m-d H:i:s",time()); break;
        }
        return $this->db->update('order',$order_id,$data) == 1;
    }
    //设置订单是否结算
    function setAllocate($order_id,$ifAllocate=true){
        $data['allocate']=$ifAllocate;
        return $this->db->update('order',$order_id,$data) == 1;
    }
    function getDetailWithoutJoin($order_id){
        $sql="SELECT * FROM `order` WHERE `id`=? and site_id=?";
        return $this->db->getOne($sql,$order_id,$this->siteId);
    }
    //订单goods详情
    function getGoodsDetail($order_id){
        $result=$this->getGoodsInOrder($order_id);
        foreach($result as &$v){
            $v['comment']=$this->getCommentDetail($v['id']);
        }
        return $result;
    }
    //订单详情 order+goods+shop
    function getDetail($order_id){
        $result['order']=$this->getDetailWithoutJoin($order_id);
        $result['goods']=$this->getGoodsInOrder($order_id);
        $result['shop']=ShopMode::init()->getDetail($result['order']['shop_id']);
        foreach($result['goods'] as &$v){
            $v['comment']=$this->getCommentDetail($v['id']);
        }
        return $result;
    }

    /**
     * 订单列表 搜出了order表信息 TODO Join table
     * @param null $user_id 按用户
     * @param null $shop_id 按商家
     * @param null $state   按状态
     * @param null $visit_state   按回访进度状态
     * @param null $byDay   按下单日期
     * @param string $type  normal|service
     * @param $allocate   0|1
     * @param null $service_id
     * @param int $rows
     * @param int $offset
     * @return array|list
     */
    function getList($user_id =null,$shop_id = null,$state = null,$visit_state=null,
                     $byDay = null,$type = null,$allocate = null,$service_id = null,
                     $rows = 20 ,$offset = 0){
        $rows=(int)$rows;
        $offset=(int)$offset;
        $condition='';
        if(!empty($user_id)){
            $user_id=(int)$user_id;
            $condition.=" AND O.`user_id`=$user_id ";
        }
        if(!empty($shop_id)){
            $condition.=" AND O.`shop_id`=".(int)$shop_id;
        }
        if(!empty($state)){
            $condition.=" AND O.`state`= ".$this->db->quote($state);
        }
        if(!empty($visit_state)){
            $condition.=" AND V.`state`= ".$this->db->quote($visit_state);
        }
        if(!empty($byDay)){ //日期格式2015-05-05
            $condition.=" AND DATE_FORMAT(`create_time`,'%Y-%m-%d')=".$this->db->quote($byDay);
        }
        if(!empty($type)){
            $condition.=" AND O.`type`= ".$this->db->quote($type);
        }
        if(!is_null($allocate)){
            $condition.=" AND O.`allocate`= ".(int)$allocate;
        }
        if(!empty($service_id)){
            $condition.=" AND O.`service_id`= ".(int)$service_id;
        }
        $sql="SELECT SQL_CALC_FOUND_ROWS O.`id`,O.`user_id`,O.shop_id,O.goods_ids,O.service_id,
              O.`order_amount`,O.`payment_amount`,O.buyer_id,O.`state`,O.`type`,
              O.create_time,O.payment_time,O.shipping_time,O.service_time,O.delivery_time,O.deal_time,
              O.express_name,O.express_num,O.remark,
              SI.`company`,SI.`tel`,SI.`qq`,SI.`user_id` AS `shop_user_id`
              FROM `shop_info` SI,`order` O
              LEFT JOIN `visit` V ON O.`id`=V.`order_id`
              WHERE O.`shop_id`=SI.`id` ".$condition." and O.site_id=?
              ORDER BY O.`create_time` DESC LIMIT $offset,$rows";
        $r=$this->db->getList($sql, $this->siteId);
        if( !empty($r) ){
            foreach ($r[0] as &$v) {
                //获取goods_in_order表订单详情
                $v['goods']=$this->getGoodsDetail($v['id']);
            }
        }
        return empty($r)?array():$r;
    }

    //订单中具体商品信息，已连接属性表，可能需要搜出更多字段
    function getGoodsInOrder($order_id){
        $data=array(
            'goods_in_order GIO'=>array('*'),
            'goods_attr GA'     =>array('name'=>'attr_name','id'=>'attr_id'),
            'goods G'           =>array('gopen_id','name','type','pic_ids','thumb_pic','bonus','commission','service_fee','platform_fee'),
            'shop_info SI'      =>array('tel','qq','company'),
            'goods_price GP'    =>array('original_price','base_price','low','medium_price','medium','high_price'),
            'picture P'         =>array('url'=>'thumb'));
        $condition=array(
            'GIO.order_id'=>$order_id,
            'GA.`id`=GIO.`attr_id`',
            'G.`id`=GIO.`goods_id`',
            'G.`shop_id`=SI.`id`',
            'GP.`id`=G.`price_id`',
            'P.`id`=G.`thumb_pic`',
            'GIO.site_id='.(int)$this->siteId);
        $sql = $this->db->selectSql($data,$condition,null,0);
        return $this->db->getAll($sql,$order_id);
    }
    //合并shareArray到cartData  一种goods对应一个share_id
    function mergeShare($cartData,$shareArray){
        foreach ($cartData as &$c) {
            $c['share_id']='';
            if(!empty($shareArray)){
                foreach ($shareArray as $k=>$s) {
                    if($c['gopen_id'] ==  $k){
                        $c['share_id'] = $s;
                    }
                }
            }
        }
        return $cartData;
    }

    //取消订单
    function cancel($order_id){
        if( $this->db->delete('order',$order_id) ==1 ){
            $sql="SELECT `id`,`goods_id`,`attr_id`,`number` FROM `goods_in_order` WHERE `order_id`=? and site_id=?";
            $ids=$this->db->getAll($sql,$order_id, $this->siteId);
            $idsSimple=array();
            foreach ($ids as $v) {
                $idsSimple[]=(int)$v['id'];
                $gopen_id=GoodsMode::init()->getGopenId($v['goods_id']);//stock change
                GoodsMode::init()->modifyStock($gopen_id,$v['attr_id'],$v['number']);
            }

            $idsStr=implode(',',$idsSimple);
            $sql="DELETE FROM `goods_in_order` WHERE `id` IN ({$idsStr})";
            return $this->db->sqlExec($sql) >= 1;
        }
        return false;
    }
    //添加/修改 运单号 ！修改完了要设置订单状态哦
    function setExpress($order_id,$express_name,$express_num){
        $data['express_name']=$express_name;
        $data['express_num']=$express_num;
        $data['shipping_time']=date('Y-m-d H:i:s',time());
        return $this->db->update('order',$order_id,$data) == 1;
    }
    //获取运单号
    function getExpress($order_id){
        $sql = "SELECT `express_name`,`express_num` FROM `order` WHERE `id`=? and site_id=?";
        return $this->db->getOne($sql,$order_id, $this->siteId);
    }
    //添加评论
    function addComment($goods_in_order_id,$user_id,$gopen_id,$comment,$score = 5,$pic_ids = null,$type = 'normal'){
        $c=CommentModule::init('goods_comment','user_id','gopen_id');
        $id=$c->add($user_id,$gopen_id,$comment,$score,$pic_ids);
        if($type == 'special') return $id>0; //大宗商品直接评
        if($id > 0){
            $data['comment_id']=(int)$id;
            return $this->db->update('goods_in_order',$goods_in_order_id,$data)==1 ? $id:-1;
        }
        return -1;
    }
    //获得评论id
    function getCommentId($goods_in_order_id){
        $sql="SELECT `comment_id` FROM `goods_in_order` WHERE `id`=? and site_id=?";
        return $this->db->getValue($sql,$goods_in_order_id, $this->siteId);
    }
    //获得订单中商品评价
    function getCommentDetail($goods_in_order_id){
        $comment_id=(int)$this->getCommentId($goods_in_order_id);
        if(!empty($comment_id)){
            return CommentModule::init('goods_comment','user_id','gopen_id')->getDetail($comment_id);
        }
        return null;
    }
    //判断订单是不是这个人的
    function checkOrderBelongsToUser($order_id,$user_id){
        $sql="SELECT 1 FROM `order` WHERE `id`=? AND `user_id`=? and site_id=?";
        return $this ->db->getExist($sql,$order_id,$user_id, $this->siteId);
    }
    function getOrderIdByCode($code){
        if(empty($code)) return null;
        $sql="SELECT id FROM `order` WHERE `code`=? AND `type`='service' and site_id=?";
        return $this ->db->getValue($sql,$code, $this->siteId);
    }

    //退货

    //添加一条退货信息
    function addRefund($order_id,$user_id,$money,$reason,$description,$type){
        $data['order_id']=$order_id;
        $data['user_id']=$user_id;
        $data['money']=$money;
        $data['reason']=$reason;
        $data['description']=$description;
        $data['type']=(int)$type;
        $data['state']='create';
        $data['site_id']=$this->siteId;
        return $this->db->insert('refund',$data,true) == 1?(int)$this->db->insertId():-1;
    }
    //买家设置退货运单号，更新shipping_time
    function setRefundExpress($id,$express_name,$express_num){
        $data['express_name']=$express_name;
        $data['express_num']=$express_num;
        $data['state']='shipped';
        $data['shipping_time']=date('Y-m-d H:i:s',time());
        return $this->db->update('refund',$id,$data) == 1;
    }
    //商家确认收到退货商品
    function setRefundConfirmState($id){
        $data['state']='confirm';
        $data['confirm_time']=date('Y-m-d H:i:s',time());
        return $this->db->update('refund',$id,$data) == 1;
    }
    //修改退货状态
    function setRefundState($id,$state){
        $data['state']=$state;
        return $this->db->update('refund',$id,$data) == 1;
    }
    // 修改是否结算过
    function setRefundAllocate($id,$allocate=true){
        $data['allocate']=$allocate;
        return $this->db->update('refund',$id,$data) == 1;
    }
    function getRefundList($user_id = null,$shop_id = null,$rows = 15,$offset=0){
        $data=array(
            'refund R'=>array('*'),
            'order O'=>array(),
            'shop_info S'=>array()
        );
        $condition=array(
            'R.`order_id`=O.`id`',
            'S.`id`=O.`shop_id`'
        );
        $condition['R.user_id']=$user_id;
        $condition['shop_id']=$shop_id;
        $condition['O.site_id']=$this->siteId;
        $sql=$this->db->selectSql($data,$condition,$rows,$offset,'R.create_time',false,'');
        return $this->db->getList($sql);
    }
    function getSimpleRefundList($state=null,$allocate=0,$rows = 15,$offset=0){
        $data=array(
            'refund R'=>array('*')
        );
        $condition=array(
            'R.allocate'=>(int)$allocate,
            'R.state'=>$state,
            'R.site_id'=>$this->siteId
        );
        $sql=$this->db->selectSql($data,$condition,$rows,$offset,'R.create_time',true,'');
        return $this->db->getList($sql);
    }
    function getRemarkOfOrder($order_id){
        $order_id=(int)$order_id;
        $goodsDetail=$this->getGoodsDetail($order_id);
        if(!empty($goodsDetail)){
            $name=$goodsDetail[0]['name'];
            $number=count($goodsDetail);
            return '购买'.mb_substr($name,0,25,'utf-8').'...等共计'.$number.'款产品';
        }
        return null;
    }
    //订单价格
    function getAmountOfOrder($order_ids){
        $sql="SELECT `order_amount`,`payment_amount` FROM `order`
              WHERE ".$this->db->getIdCondition($order_ids,'id');
        return $this->db->getAll($sql);
    }
    //获得服务商品验证码
    function getServiceCode($order_id){
        $sql="SELECT `code` FROM `order` WHERE `id`=? and site_id=?";
        return $this->db->getValue($sql,$order_id, $this->siteId);
    }
    //服务商品验证码
    function insertCode($order_id,$code){
        $data['code']=$code;
        return $this->db->update('order',$order_id,$data) == 1?(int)$this->db->insertId():-1;
    }
    function getGoodsIdByGoodsInOrderId($id){
        $sql="SELECT `goods_id` FROM `goods_in_order` WHERE `id`=? and site_id=?";
        return $this->db->getValue($sql,$id, $this->siteId);
    }
    //在goods_in_order表添加comment_id
    function addCommentId($id,$comment_id){
        $data['comment_id']=$comment_id;
        return $this->db->update('goods_in_order',$id,$data) == 1;
    }
    //支付成功后，检查订单是否处理了,已经处理过？not used now
    function checkOrderDealed($order_id){
        $orderInfo=$this->getDetailWithoutJoin($order_id);
        return $orderInfo['state']=='unpaid' ? false:true;
    }
}